package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.EnterpriseFilesTree;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.domain.TeamFilesTree;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.mapper.EnterpriseFilesTreeMapper;
import cn.cdeden.knowledge.mapper.PersonalFilesTreeMapper;
import cn.cdeden.knowledge.mapper.TeamFilesTreeMapper;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cdeden.knowledge.mapper.FilesCollectionMapper;
import cn.cdeden.knowledge.domain.FilesCollection;
import cn.cdeden.knowledge.service.FilesCollectionService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@RequiredArgsConstructor
public class FilesCollectionServiceImpl extends ServiceImpl<FilesCollectionMapper, FilesCollection> implements FilesCollectionService{

    private final FilesCollectionMapper filesCollectionMapper;

    private final PersonalFilesTreeMapper personalFilesTreeMapper;

    private final TeamFilesTreeMapper teamFilesTreeMapper;

    private final EnterpriseFilesTreeMapper enterpriseFilesTreeMapper;

    @Override
    public void deleteLibTaggedData(String type, List<String> treeNodeIds) {
        QueryWrapper<FilesCollection> queryWrapper = new QueryWrapper<FilesCollection>().in("tree_node_id", treeNodeIds).eq("file_type", type);
        filesCollectionMapper.delete(queryWrapper);
    }

    @Override
    public int insert(FilesCollectionDto resources) throws BadRequestException {
        FilesCollection entity = MapstructUtils.convert(resources, FilesCollection.class);
//        FilesCollection entity = ConvertUtil.convert(resources, FilesCollection.class);
        switch (resources.getFileType()) {
            case "0": {
                //查找个人文档库
                PersonalFilesTree personalFilesTree = personalFilesTreeMapper.selectById(resources.getTreeNodeId());
                if (personalFilesTree == null)
                    throw new BadRequestException("错误的文件或文件夹");
                entity.setRealName(personalFilesTree.getRealName());
                break;
            }
            case "1": {
                //查找团队文档库
                TeamFilesTree teamFilesTree = teamFilesTreeMapper.selectById(resources.getTreeNodeId());
                if (teamFilesTree == null)
                    throw new BadRequestException("错误的文件或文件夹");
                entity.setTeamId(teamFilesTree.getTeamId());
                entity.setRealName(teamFilesTree.getRealName());
                break;
            }
            case "2": {
                //查找企业文档库
                EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeMapper.selectById(resources.getTreeNodeId());
                if (enterpriseFilesTree == null)
                    throw new BadRequestException("错误的文件或文件夹");
                entity.setRealName(enterpriseFilesTree.getRealName());
                entity.setLibraryId(enterpriseFilesTree.getLibraryId());
                break;
            }
//            case "3": {
//                //查找团队
//                Team team = teamService.getById(resources.getTreeNodeId());
//                if (team == null)
//                    throw new BadRequestException("错误的文件或文件夹");
//                resources.setRealName(team.getTeamName());
//            }
        }
        return filesCollectionMapper.insert(entity);
    }

    @Override
    public int removeByMap(FilesCollectionDto resources) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("file_type", resources.getFileType());
        map.put("user_id", resources.getUserId());
        map.put("tree_node_id", resources.getTreeNodeId());
        return filesCollectionMapper.deleteByMap(map);
    }

    @Override
    public TableDataInfo<FilesTree> queryAll(FilesCollectionQueryParam query, Pageable pageable) {
        Long userId = LoginHelper.getLoginUser().getUserId();
//        Long userId = FileUserUtils.getUser().getId();
//        IPage<FilesCollection> queryPage = PageUtil.toMybatisPage(pageable);
//        QueryWrapper<FilesCollection> predicate = QueryHelpMybatisPlus.getPredicate(query);
        String fileType = query.getFileType();
        String teamId = query.getTeamId();
//        predicate.eq("user_id", userId);
        List<FilesCollection> records = filesCollectionMapper.queryAll(fileType,query.getLibraryId(),teamId,query.getRealName(), String.valueOf(userId), query.getNameSort(),pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
        int count = filesCollectionMapper.queryAllCount(fileType,query.getLibraryId(),teamId,query.getRealName(), String.valueOf(userId), query.getNameSort());
        List<FilesTree> list = new ArrayList<>();
        List<String> integers = records.stream().map(FilesCollection::getTreeNodeId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(integers)) {
//            return new PageInfo<>(count, list, pageable.getPageNumber(), pageable.getPageSize());
            return new TableDataInfo<>(list, count, pageable.getPageNumber(), pageable.getPageSize());
        }
        switch (fileType) {
            case "0": {
                //查找个人文档库
                PersonalFilesTreeParam queryParam = new PersonalFilesTreeParam();
                queryParam.setSortAsc(query.getSortAsc());
                queryParam.setSortDesc(query.getSortDesc());
                QueryWrapper<PersonalFilesTree> treeQueryWrapper = QueryHelpMybatisPlus.getPredicate(queryParam);
                treeQueryWrapper.in("id",integers);
                List<PersonalFilesTree> personalFilesTrees = personalFilesTreeMapper.selectList(treeQueryWrapper);
                List<FilesTree> convert = MapstructUtils.convert(personalFilesTrees, FilesTree.class);
//                List<FilesTree> convert = ConvertUtil.convertList(personalFilesTrees, FilesTree.class);
                convert.forEach(filesTree -> filesTree.setLibraryType(TreeEnum.PERSONAL.getType()));
                list = convert;
                break;
            }
            case "1": {
                //查找团队文档库
                TeamCollectionTreeQueryParam queryParam = new TeamCollectionTreeQueryParam();
                queryParam.setSortAsc(query.getSortAsc());
                queryParam.setSortDesc(query.getSortDesc());
                QueryWrapper<TeamFilesTree> treeQueryWrapper = QueryHelpMybatisPlus.getPredicate(queryParam);
                treeQueryWrapper.in("id",integers);
                List<TeamFilesTree> teamFilesTrees = teamFilesTreeMapper.selectList(treeQueryWrapper);
                List<FilesTree> convert = MapstructUtils.convert(teamFilesTrees, FilesTree.class);
                convert.forEach(filesTree -> filesTree.setLibraryType("teamFile"));
                list = convert;
                break;
            }
            case "2": {
                //查找企业文档库
                EnterpriseFilesTreeQueryParam queryParam = new EnterpriseFilesTreeQueryParam();
                ArrayList<String> strings = new ArrayList<>();
                if (query.getSortAsc()!=null) {
                    query.getSortAsc().forEach(s -> strings.add(s+" ASC"));
                }


                if (query.getSortDesc()!=null){
                    query.getSortDesc().forEach(s -> strings.add(s+" DESC"));
                }

                queryParam.setSort(strings);
//                queryParam.setSort(query.getSortDesc());
                QueryWrapper<EnterpriseFilesTree> treeQueryWrapper = QueryHelpMybatisPlus.getPredicate(queryParam);
                treeQueryWrapper.in("id",integers);
                List<EnterpriseFilesTree> filesTrees = enterpriseFilesTreeMapper.selectList(treeQueryWrapper);
                List<FilesTree> convert = MapstructUtils.convert(filesTrees, FilesTree.class);
//                List<FilesTree> convert = ConvertUtil.convertList(filesTrees, FilesTree.class);
                convert.forEach(filesTree -> filesTree.setLibraryType("enterprise"));
                list = convert;
                break;
            }
//            case "3": {
//                //查找团队
//                List<Team> filesTrees = teamService.listByIds(integers);
//                List<FilesTree> convert = ConvertUtil.convertList(filesTrees, FilesTree.class);
//                convert.forEach(filesTree -> filesTree.setLibraryType("team"));
//                list = convert;
//                break;
//            }
        }

//        return new PageInfo<>(count, list, pageable.getPageNumber(), pageable.getPageSize());
        return new TableDataInfo<>(list, count, pageable.getPageNumber(), pageable.getPageSize());
    }
}
